﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using SmartSpace.Core;
using System.IO;

namespace SmartSpace.Packaging
{
    public class XMemberUtil
    {
        public static List<OrgMember> Load(string filePath)
        {
            XDocument xDoc = XDocument.Load(filePath);
            return Load(xDoc);
        }

        public static List<OrgMember> Load(Stream stream)
        {
            XDocument xDoc = XDocument.Load(stream);
            return Load(xDoc);
        }

        private static List<OrgMember> Load(XDocument xDoc)
        {
            List<OrgMember> members = new List<OrgMember>();
            IEnumerable<XElement> elements = xDoc.Root.Elements("member");
            foreach (var item in elements)
            {
                OrgMember member = new OrgMember();
                member.Id = new Guid(item.Attribute("id").Value);
                Org org = new Org();
                org.Code = item.Attribute("org-code").Value;
                member.Org = org;
                User user = new User();
                user.Account = item.Attribute("user-account").Value;
                member.User = user;
                member.IsMajor = Convert.ToBoolean(item.Attribute("is-major").Value);
                members.Add(member);
            }
            return members;
        }

        public static bool Save(List<OrgMember> members, string filePath)
        {
            XDocument xDoc = new XDocument();
            xDoc.Add(new XElement("members"));
            foreach (var item in members)
            {
                xDoc.Root.Add(new XElement("member",
                    new XAttribute("id", item.Id),
                    new XAttribute("org-code", item.Org.Code),
                    new XAttribute("user-account", item.User.Account),
                    new XAttribute("is-major", item.IsMajor)));
            }
            xDoc.Save(filePath);
            return true;
        }
    }
}
